package com.huangdada.hfweather.service.impl;

import com.huangdada.hfweather.bean.City;
import com.huangdada.hfweather.bean.ReadExcel;
import com.huangdada.hfweather.bean.SJCity;
import com.huangdada.hfweather.mapper.CityMapper;
import com.huangdada.hfweather.service.CityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 城市的业务逻辑实现
 * @PROJECT_NAME: hf-weather
 * @CLASS_NAME:
 * @Author: huanglibin
 * @Date: 2020-03-31 21:51
 * @Version: 1.0
 */
@Slf4j
@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper cityMapper;

    /**
     * 创建一个线程池
     */
    private static ThreadPoolExecutor threadPoolExecutor;

    static {
        threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
    }

    @Override
    public void importCityAll(String name, MultipartFile file) {
        //处理Excel
        ReadExcel re = new ReadExcel();
        //解析Excel，获得Excel数据集
        List<City> cityList = re.getExcelInfo(name,file);
        threadPoolExecutor.execute(new ExcelRunnable(cityList));
    }

    /**
     * 执行Excel批量插入线程操作
     */
    private class ExcelRunnable implements Runnable{

        List<City> cityList;

        public ExcelRunnable(List<City> cityList){
            this.cityList = cityList;
        }

        @Override
        public void run() {
            //处理数据库，插入数据
            for (City city : cityList) {
                Integer result = cityMapper.addCityInfo(city);
                if (result > 0) {
                    log.info("当前线程名称为："+Thread.currentThread().getName()+"批量插入数据成功！");
                } else {
                    log.info("批量插入数据失败！");
                }
            }
        }
    }

    @Override
    public List<City> getCityList() {
        return cityMapper.queryCitys();
    }

    @Override
    public Integer addSJCityInfo(SJCity city) {
        return cityMapper.addSJCityInfo(city);
    }

    @Override
    public List<SJCity> getSJCityList() {
        return cityMapper.querySjCitys();
    }


}
